const dayjs = require('dayjs');
const pageHelper = require('../../../../../helper/page_helper.js');
const cloudHelper = require('../../../../../helper/cloud_helper.js');
const Day = require('../../../../../miniprogram_npm/dayjs');
const { createStoreBindings } = require('mobx-miniprogram-bindings');
const { taskStore } = require('../../../../../store/modules/task_store.js');
const { projectStore } = require('../../../../../store/modules/project_store.js');
const { userStore } = require('../../../../../store/global/user_store.js');

Page({
  data: {
    isLoad: false,
    isLoading: true,
    taskId: null,
    task: {
      title: '',
      projectId: '',
      priority: 'medium',
      assigneeId: '',
      startDate: '',
      dueDate: '',
      description: '',
      subtasks: []
    },
    projectIndex: -1,
    priorityIndex: 1, // 默认选中"中"优先级
    assigneeIndex: -1,
    
    // 选项数据
    projects: [],
    priorities: [
      { value: 'low', text: '低' },
      { value: 'medium', text: '中' },
      { value: 'high', text: '高' },
      { value: 'urgent', text: '紧急' }
    ],
    members: [],
    
    // 表单验证错误
    errors: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 创建 TaskStore 绑定
    this.taskStoreBindings = createStoreBindings(this, {
      store: taskStore,
      fields: [
        'currentTask'
      ],
      actions: [
        'getTaskDetail',
        'createTask',
        'updateTask'
      ]
    });
    
    // 创建 ProjectStore 绑定
    this.projectStoreBindings = createStoreBindings(this, {
      store: projectStore,
      fields: [
        'projects'
      ],
      actions: [
        'getProjectList'
      ]
    });
    
    // 创建 UserStore 绑定
    this.userStoreBindings = createStoreBindings(this, {
      store: userStore,
      fields: [
        'departmentMembers'
      ],
      actions: [
        'getDepartmentMembers'
      ]
    });
    
    this.options = options;
    
    // 初始化基础数据
    this._initBaseData();
  },
  
  /**
   * 初始化基础数据
   */
  async _initBaseData() {
    try {
      this.setData({ 
        isLoading: true,
        taskId: this.options.id || null
      });
      
      // 加载项目列表
      await this.getProjectList();
      
      // 加载团队成员
      await this.getDepartmentMembers();
      
      // 处理项目和成员数据
      this.setData({
        projects: this.data.projects.map(p => ({
          id: p._id,
          name: p.name
        })),
        members: this.data.departmentMembers.map(m => ({
          id: m._id,
          name: m.name
        }))
      });
      
      // 加载任务数据（编辑模式）或初始化新任务（新建模式）
      if (this.data.taskId) {
        await this._loadTaskDetail();
      } else {
        this._initNewTask();
      }
      
      this.setData({
        isLoad: true,
        isLoading: false
      });
    } catch (err) {
      console.error('[任务编辑] 初始化数据失败:', err);
      pageHelper.showErrToast('数据加载失败，请重试');
      this.setData({
        isLoad: true,
        isLoading: false
      });
    }
  },
  
  /**
   * 加载任务详情（编辑模式）
   */
  async _loadTaskDetail() {
    try {
      await this.getTaskDetail(this.data.taskId);
      
      if (!this.data.currentTask) {
        pageHelper.showErrToast('未找到任务数据');
        return;
      }
      
      // 设置表单初始值
      const task = this.data.currentTask;
      
      this.setData({
        task: {
          title: task.title || '',
          projectId: task.projectId || '',
          priority: task.priority || 'medium',
          assigneeId: task.assigneeId || '',
          startDate: task.startDate ? Day(task.startDate).format('YYYY-MM-DD') : '',
          dueDate: task.dueDate ? Day(task.dueDate).format('YYYY-MM-DD') : '',
          description: task.description || '',
          subtasks: task.subtasks || []
        },
        projectIndex: this.data.projects.findIndex(p => p.id === task.projectId),
        priorityIndex: this.data.priorities.findIndex(p => p.value === task.priority),
        assigneeIndex: this.data.members.findIndex(m => m.id === task.assigneeId)
      });
    } catch (err) {
      console.error('[任务编辑] 加载任务详情失败:', err);
      pageHelper.showErrToast('加载任务详情失败');
    }
  },
  
  /**
   * 初始化新任务（新建模式）
   */
  _initNewTask() {
    // 如果URL参数中有项目ID，预设项目
    const projectId = this.options.projectId || '';
    const projectIndex = projectId ? this.data.projects.findIndex(p => p.id === projectId) : -1;
    
    // 设置当前日期为开始日期
    const today = Day().format('YYYY-MM-DD');
    
    this.setData({
      task: {
        ...this.data.task,
        projectId: projectId,
        startDate: today,
        dueDate: Day().add(7, 'day').format('YYYY-MM-DD')
      },
      projectIndex
    });
  },

  /**
   * 项目选择器变化
   */
  onProjectChange(e) {
    const index = e.detail.value;
    this.setData({
      projectIndex: index,
      'task.projectId': this.data.projects[index].id,
      errors: { ...this.data.errors, projectId: '' }
    });
  },

  /**
   * 优先级选择器变化
   */
  onPriorityChange(e) {
    const index = e.detail.value;
    this.setData({
      priorityIndex: index,
      'task.priority': this.data.priorities[index].value,
      errors: { ...this.data.errors, priority: '' }
    });
  },

  /**
   * 负责人选择器变化
   */
  onAssigneeChange(e) {
    const index = e.detail.value;
    this.setData({
      assigneeIndex: index,
      'task.assigneeId': this.data.members[index].id,
      errors: { ...this.data.errors, assigneeId: '' }
    });
  },

  /**
   * 开始时间选择器变化
   */
  onStartDateChange(e) {
    this.setData({
      'task.startDate': e.detail.value,
      errors: { ...this.data.errors, startDate: '' }
    });
  },

  /**
   * 截止时间选择器变化
   */
  onDueDateChange(e) {
    this.setData({
      'task.dueDate': e.detail.value,
      errors: { ...this.data.errors, dueDate: '' }
    });
  },

  /**
   * 添加子任务
   */
  addSubtask() {
    const subtasks = this.data.task.subtasks || [];
    subtasks.push({
      id: 'temp_' + dayjs().valueOf(),
      title: '',
      status: 'pending'
    });
    this.setData({
      'task.subtasks': subtasks
    });
  },

  /**
   * 子任务输入变化
   */
  onSubtaskInput(e) {
    const index = e.currentTarget.dataset.index;
    const value = e.detail.value;
    const subtasks = this.data.task.subtasks;
    subtasks[index].title = value;
    this.setData({
      'task.subtasks': subtasks
    });
  },

  /**
   * 删除子任务
   */
  deleteSubtask(e) {
    const index = e.currentTarget.dataset.index;
    const subtasks = this.data.task.subtasks;
    subtasks.splice(index, 1);
    this.setData({
      'task.subtasks': subtasks
    });
  },

  /**
   * 表单提交
   */
  async formSubmit(e) {
    try {
      const formData = e.detail.value;
      const task = {
        ...this.data.task,
        title: formData.title,
        description: formData.description
      };
      
      // 表单验证
      if (!this._validateForm(task)) {
        return;
      }
      
      // 显示加载中
      wx.showLoading({
        title: '保存中...',
        mask: true
      });
      
      // 格式化数据
      const taskData = this._formatTaskData(task);
      
      // 根据是否有ID决定是创建还是更新
      if (this.data.taskId) {
        await this.updateTask(taskData);
      } else {
        await this.createTask(taskData);
      }
      
      // 关闭加载提示
      wx.hideLoading();
      
      // 显示成功提示
      pageHelper.showSuccToast('保存成功');
      
      // 返回上一页
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    } catch (err) {
      console.error('[任务编辑] 保存失败:', err);
      wx.hideLoading();
      pageHelper.showErrToast('保存失败，请重试');
    }
  },
  
  /**
   * 表单验证
   */
  _validateForm(task) {
    const errors = {};
    
    if (!task.title.trim()) {
      errors.title = '请输入任务标题';
    }
    
    if (!task.projectId) {
      errors.projectId = '请选择所属项目';
    }
    
    if (!task.priority) {
      errors.priority = '请选择优先级';
    }
    
    if (!task.assigneeId) {
      errors.assigneeId = '请选择负责人';
    }
    
    if (!task.startDate) {
      errors.startDate = '请选择开始时间';
    }
    
    if (!task.dueDate) {
      errors.dueDate = '请选择截止时间';
    }
    
    // 验证子任务
    const invalidSubtasks = task.subtasks.some(item => !item.title.trim());
    if (invalidSubtasks) {
      errors.subtasks = '请填写所有子任务名称';
    }
    
    // 如果有错误，显示第一个错误并更新错误状态
    if (Object.keys(errors).length > 0) {
      const firstError = Object.values(errors)[0];
      pageHelper.showErrToast(firstError);
      this.setData({ errors });
      return false;
    }
    
    return true;
  },
  
  /**
   * 格式化提交的任务数据
   */
  _formatTaskData(task) {
    // 格式化数据用于提交
    return {
      _id: this.data.taskId,
      title: task.title,
      projectId: task.projectId,
      priority: task.priority,
      assigneeId: task.assigneeId,
      startDate: task.startDate,
      dueDate: task.dueDate,
      description: task.description,
      subtasks: task.subtasks.map(item => ({
        title: item.title,
        status: item.status || 'pending',
        _id: item._id || undefined
      }))
    };
  },

  /**
   * 取消编辑
   */
  cancelEdit() {
    wx.navigateBack();
  },
  
  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    // 清理 store 绑定
    if (this.taskStoreBindings) {
      this.taskStoreBindings.destroyStoreBindings();
    }
    
    if (this.projectStoreBindings) {
      this.projectStoreBindings.destroyStoreBindings();
    }
    
    if (this.userStoreBindings) {
      this.userStoreBindings.destroyStoreBindings();
    }
  }
}); 